<script setup lang="ts">
import {
  VxeButtonEvents,
  VxeFormEventProps,
  VXETable,
  VxeTableEvents,
  VxeTableInstance,
  VxeToolbarInstance,
  VxeTablePropTypes,
  VxeFormPropTypes
} from "vxe-table";
import ReCol from "@/components/ReCol";
import { http } from "@/utils/http";
import { reactive, ref, toRefs, watch, onMounted } from "vue";

import {
  PfmeaData,
  InsertPfmeaData,
  EditePfmeaData,
  DeletePfmeaData
} from "./pfmea_file_manage";
import { object } from "vue-types";

defineOptions({
  name: "pfmea_file_manage"
});

const props = defineProps([
  "Info",
  "stationList",
  "userInfo",
  "base",
  "base_zone",
  "partName"
]);

interface Info {
  pfmea_number: string;
  partNumber: string;
  partName: string;
  responsibility: string;
  keyDate: string;
  editDate: string;
  editor: string;
  coreTeam: string;
  version: string;
}
interface pfmeaDataRow {
  id: number;
  ProcessFunction: string;
  PotentialFailureMode: string;
  PotentialEffectsOfFailure: string;
  Severity: string;
  Class: string;
  PotentialCausesOfFailure: string;
  Occurence: string;
  CurrentProcessControlsPrevention: string;
  CurrentProcessControlsDetection: string;
  Detection: string;
  Rpn: string;
  SeverZone: string;
  DetectZone: string;
  RiskPriorLevel: string;
  RecommendedActions: string;
  ResponsibilityAndTargetCompletionDate: string;
  ActionTaken: string;
  ActionTakenSeverity: string;
  ActionTakenOccurence: string;
  ActionTakenDetection: string;
  ActionTakenRpn: string;
}
const xTable = ref<VxeTableInstance<pfmeaDataRow>>();
//定义响应式对象
const pageData: any = reactive({
  modify_info: {
    pfmea_number: "",
    partNumber: "",
    partName: "",
    responsibility: "",
    keyDate: "",
    editDate: "",
    editor: "",
    coreTeam: "",
    version: ""
  },
  pfmeadata: []
});
//将响应式对象中的属性变为单独的响应式ref对象
const { modify_info, pfmeadata } = toRefs(pageData);
//定义修改和新增表单中的响应式对象
const pfmeaFormData = reactive({
  ProcessFunction: "",
  PotentialFailureMode: "",
  PotentialEffectsOfFailure: "",
  Severity: "",
  Class: "",
  PotentialCausesOfFailure: "",
  Occurence: "",
  CurrentProcessControlsPrevention: "",
  CurrentProcessControlsDetection: "",
  Detection: "",
  Rpn: "",
  SeverZone: "",
  DetectZone: "",
  RiskPriorLevel: "",
  RecommendedActions: "",
  ResponsibilityAndTargetCompletionDate: "",
  ActionTaken: "",
  ActionTakenSeverity: "",
  ActionTakenOccurence: "",
  ActionTakenDetection: "",
  ActionTakenRpn: ""
});
//将当前组件的属性中的Info对象转变为响应式对象info
const info = ref(props.Info);
//表单规则
const pfmeaFormRules = reactive<VxeFormPropTypes.Rules>({
  ProcessFunction: [
    {
      required: true,
      message: "请输入过程名称"
    },
    {
      min: 3,
      max: 50,
      message: "长度在3到50个字符"
    }
  ]
});
const submitLoading = ref(false);
const showEdit = ref(false);
const selectRow = ref<pfmeaDataRow | null>();
const tableData = ref<pfmeaDataRow[]>([]);

const xToolbar = ref({} as VxeToolbarInstance);
//创建工位响应式对象station
const station = ref("");
const allAlign: any = ref("center");

let updateEditor = [];

const insertEvent = () => {
  Object.assign(pfmeaFormData, {
    // 补充pfmeaFormData中没有的信息，合并到pfmeaFormData中
    base: props.base,
    base_zone: props.base_zone,
    pfmea_op: station,
    pfmea_info: props.partName
  });
  selectRow.value = null;
  showEdit.value = true;
};
const editEvent = (row: pfmeaDataRow) => {
  Object.assign(pfmeaFormData, row);
  selectRow.value = row;
  showEdit.value = true;
};
const cellDBLClickEvent: VxeTableEvents.CellDblclick<pfmeaDataRow> = ({
  row
}) => {
  editEvent(row);
};
const removeEvent = async (row: pfmeaDataRow) => {
  const type = await VXETable.modal.confirm("您确定要删除该数据?");
  if (type === "confirm") {
    const $table = xTable.value;
    if ($table) {
      $table.remove(row);
      console.log("当前处于删除模式！");

      const delete_row = { ...row };
      console.log(delete_row);
      DeletePfmeaData(delete_row)
        .then(res => {
          const res2: any = res;
          VXETable.modal.message({
            content: res2.result_info,
            status: res2.status
          });
        })
        .catch(err => {
          VXETable.modal.message({
            content: err,
            status: "error"
          });
        });
    }
  }
};

const submitEvent = () => {
  submitLoading.value = true;
  setTimeout(() => {
    const $table = xTable.value;
    if ($table) {
      submitLoading.value = false;
      showEdit.value = false;
      if (selectRow.value) {
        console.log("当前处于编辑模式！");
        // console.log(selectRow.value);
        // VXETable.modal.message({ content: "保存成功啦~", status: "success" });
        Object.assign(selectRow.value, pfmeaFormData);
        console.log({ ...pfmeaFormData });
        EditePfmeaData({ ...pfmeaFormData })
          .then(res => {
            const res2: any = res;
            VXETable.modal.message({
              content: res2.result_info,
              status: res2.status
            });
          })
          .catch(err => {
            VXETable.modal.message({
              content: err,
              status: "error"
            });
          });
      } else {
        console.log("当前处于新增模式！");
        $table.insert({ ...pfmeaFormData });
        console.log(pfmeaFormData);
        console.log({ ...pfmeaFormData });
        //插入新增的数据
        InsertPfmeaData({ ...pfmeaFormData })
          .then(res => {
            const res2: any = res;
            VXETable.modal.message({
              content: res2.result_info,
              status: res2.status
            });
          })
          .catch(err => {
            VXETable.modal.message({
              content: err,
              status: "error"
            });
          });
      }
    }
  }, 500);
};

//监控工位下拉框状态，当选择新的工位时发起请求接口，获取响应数据赋值给响应式对象
watch(station, newStation => {
  console.log("station变化了", newStation);
  PfmeaData(pfmeadata, {
    base: props.base,
    base_zone: props.base_zone,
    partName: props.partName,
    pfmea_op: newStation
  });
});

// 定义一个显示第一个工位的定时器函数
const showFirstOpInfo = () => {
  setTimeout(() => {
    console.log("pfmea_file_manage组件挂载啦vvv");
    console.log(props.stationList[0]);
    station.value = props.stationList[0];
  }, 500);
};

//组件挂载后加载显示第一个工位信息
onMounted(() => {
  showFirstOpInfo();
});
</script>

<template>
  <el-card class="box-card" shadow="hover">
    <el-row :gutter="20" justify="space-between">
      <re-col :value="24" :md="12" :xs="24">
        <el-text tag="b">工位选择：</el-text>
        <el-select style="width: 240px" clearable v-model="station">
          <el-option
            v-for="item in stationList"
            :key="item"
            :label="item"
            :value="item"
          />
          <!-- <el-option v-for="(item, index) in stationList" :key="index">
            {{ item }}
          </el-option> -->
        </el-select>
      </re-col>
      <re-col :value="8" :md="12" :xs="24">
        <el-tooltip
          class="box-item"
          effect="dark"
          :content="info.pfmea_number"
          placement="top-start"
        >
          <div style="max-height: 21px; overflow: hidden">
            <el-text tag="b">PFMEA编号：</el-text> {{ info.pfmea_number }}
          </div>
        </el-tooltip>
      </re-col>
      <re-col :value="8" :md="12" :xs="24">
        <el-tooltip
          class="box-item"
          effect="dark"
          :content="info.partNumber"
          placement="top-start"
          ><div style="max-height: 21px; overflow: hidden">
            <el-text tag="b">零件编号：</el-text>{{ info.partNumber }}
          </div>
        </el-tooltip>
      </re-col>
      <re-col :value="8" :md="12" :xs="24"
        ><el-text tag="b">机型：</el-text>{{ info.partName }}</re-col
      >
      <re-col :value="8" :md="12" :xs="24">
        <el-text tag="b">工艺责任：</el-text>
        {{ info.responsibility }}
      </re-col>

      <re-col :value="8" :md="12" :xs="24">
        <el-text tag="b">关键日期：</el-text>{{ info.keyDate }}
      </re-col>
      <re-col :value="8" :md="12" :xs="24">
        <el-text tag="b">更新信息：</el-text>
        <span v-show="info.editDate"
          >{{ info.editor }}于{{ info.editDate }}修改</span
        >
      </re-col>
      <re-col :value="8" :md="12" :xs="24">
        <el-tooltip
          class="box-item"
          effect="dark"
          :content="info.editor"
          placement="top-start"
        >
          <div style="max-height: 21px; overflow: hidden">
            <el-text tag="b">编制人：</el-text>{{ info.editor }}
          </div>
        </el-tooltip>
      </re-col>

      <re-col :value="8" :md="12" :xs="24">
        <el-tooltip
          class="box-item"
          effect="dark"
          :content="info.coreTeam"
          placement="top-start"
        >
          <div style="max-height: 21px; overflow: hidden">
            <el-text tag="b">核心小组：</el-text>{{ info.coreTeam }}
          </div>
        </el-tooltip>
      </re-col>
      <re-col :value="8" :md="12" :xs="24">
        <div style="max-height: 21px; overflow: hidden">
          <el-text tag="b">PFMEA版本号：</el-text>{{ info.version }}
        </div>
      </re-col>
    </el-row>
  </el-card>
  <vxe-toolbar>
    <template #buttons>
      <vxe-button icon="fa fa-plus" @click="insertEvent()">新增</vxe-button>
      <el-text style="margin-left: 10px"
        >[🐰🐇❤️Tips]：按住<span style="color: red">"【shift】 + 鼠标滚轮"</span
        >，可实现左右滑动页面~</el-text
      >
    </template>
  </vxe-toolbar>
  <vxe-table
    :align="allAlign"
    :data="pfmeadata"
    ref="xTable"
    border
    round
    :header-cell-style="{
      backgroundColor: '#005987',
      color: 'white',
      opacity: 0.8
    }"
    auto-resize
    :sort-config="{ multiple: true, trigger: 'cell' }"
    :export-config="{ type: 'csv' }"
  >
    <vxe-column type="seq" width="60"></vxe-column>
    <vxe-column
      field="ProcessFunction"
      title="过程步骤/功能"
      sortable
      width="135"
    ></vxe-column>
    <vxe-column
      field="PotentialFailureMode"
      title="潜在失效模式"
      sortable
      width="130"
    ></vxe-column>
    <vxe-column
      field="PotentialEffectsOfFailure"
      title="潜在失效后果"
      sortable
      width="350"
    ></vxe-column>
    <vxe-column
      field="Severity"
      title="严重度S"
      sortable
      width="95"
    ></vxe-column>
    <vxe-column field="Class" title="分类" sortable width="100"></vxe-column>
    <vxe-column
      field="PotentialCausesOfFailure"
      title="潜在失效原因"
      sortable
      width="200"
    ></vxe-column>
    <vxe-column
      field="Occurence"
      title="频度O"
      sortable
      width="95"
    ></vxe-column>
    <vxe-column
      field="CurrentProcessControlsPrevention"
      title="控制计划的预防"
      sortable
      width="100"
    ></vxe-column>
    <vxe-column
      field="CurrentProcessControlsDetection"
      title="控制计划的探测"
      sortable
      width="400"
    ></vxe-column>
    <vxe-column
      field="Detection"
      title="探测度D"
      sortable
      width="95"
    ></vxe-column>
    <vxe-column field="Rpn" title="RPN" sortable width="95"></vxe-column>
    <vxe-column
      field="SeverZone"
      title="严重区"
      sortable
      width="95"
    ></vxe-column>
    <vxe-column
      field="DetectZone"
      title="探测区"
      sortable
      width="95"
    ></vxe-column>
    <vxe-column
      field="RiskPriorLevel"
      title="RPL"
      sortable
      width="95"
    ></vxe-column>
    <vxe-colgroup title="措施执行结果">
      <vxe-column
        field="RecommendedActions"
        title="建议措施"
        sortable
        width="150"
      ></vxe-column>
      <vxe-column
        field="ResponsibilityAndTargetCompletionDate"
        title="责任人和目标完成日期"
        sortable
        width="170"
      ></vxe-column>

      <vxe-column
        field="ActionTaken"
        title="实施对策"
        sortable
        width="450"
      ></vxe-column>
      <vxe-column
        field="ActionTakenSeverity"
        title="严重度S"
        sortable
        width="95"
      ></vxe-column>
      <vxe-column
        field="ActionTakenOccurence"
        title="频度O"
        sortable
        width="95"
      ></vxe-column>
      <vxe-column
        field="ActionTakenDetection"
        title="探测度D"
        sortable
        width="95"
      ></vxe-column>
      <vxe-column
        field="ActionTakenRpn"
        title="RPN"
        sortable
        width="95"
      ></vxe-column>
    </vxe-colgroup>
    <vxe-column title="操作" width="90" fixed="right">
      <template #default="{ row }">
        <vxe-button
          type="text"
          icon="vxe-icon-edit"
          @click="editEvent(row)"
        ></vxe-button>
        <vxe-button
          type="text"
          icon="vxe-icon-delete"
          @click="removeEvent(row)"
        ></vxe-button>
      </template>
    </vxe-column>
  </vxe-table>
  <!-- <vxe-pager
    align="left"
    v-model:current-page="page1.currentPage"
    v-model:page-size="page1.pageSize"
    :total="page1.totalResult"
  >
  </vxe-pager> -->
  <!-- //数据编辑 -->
  <vxe-modal
    v-model="showEdit"
    :title="selectRow ? '编辑PFMEA' : '新增PFMEA'"
    width="70%"
    height="80%"
    min-width="600"
    min-height="300"
    :loading="submitLoading"
    resize
    destroy-on-close
  >
    <template #default>
      <vxe-form
        :data="pfmeaFormData"
        :rules="pfmeaFormRules"
        title-align="right"
        title-width="110"
        @submit="submitEvent"
      >
        <vxe-form-item
          title="修改信息"
          title-align="left"
          :title-width="200"
          :span="24"
          :title-prefix="{ icon: 'vxe-icon--info' }"
        ></vxe-form-item>
        <vxe-form-item
          field="reason"
          title="修改原因"
          :span="24"
          :item-render="{}"
        >
          <template #default="{ data }">
            <vxe-textarea
              v-model="data.reason"
              placeholder="请输入修改原因"
              :autosize="{ minRows: 2, maxRows: 4 }"
            ></vxe-textarea>
          </template>
        </vxe-form-item>
        <vxe-form-item
          field="description"
          title="修改描述"
          :span="24"
          :item-render="{}"
        >
          <template #default="{ data }">
            <vxe-textarea
              v-model="data.description"
              placeholder="请输入修改描述"
              :autosize="{ minRows: 2, maxRows: 4 }"
            ></vxe-textarea>
          </template>
        </vxe-form-item>
        <vxe-form-item
          title="现行过程"
          title-align="left"
          :title-width="200"
          :span="24"
          :title-prefix="{ icon: 'vxe-icon--warning' }"
        ></vxe-form-item>
        <vxe-form-item
          field="ProcessFunction"
          title="过程步骤/功能"
          :span="12"
          :item-render="{}"
        >
          <template #default="{ data }">
            <vxe-textarea
              v-model="data.ProcessFunction"
              placeholder="请输入过程步骤/功能"
              :autosize="{ minRows: 4, maxRows: 6 }"
            ></vxe-textarea>
          </template>
        </vxe-form-item>
        <vxe-form-item
          field="PotentialFailureMode"
          title="潜在失效模式"
          :span="12"
          :item-render="{}"
        >
          <template #default="{ data }">
            <vxe-textarea
              v-model="data.PotentialFailureMode"
              placeholder="请输入潜在失效模式"
              :autosize="{ minRows: 4, maxRows: 6 }"
            ></vxe-textarea>
          </template>
        </vxe-form-item>
        <vxe-form-item
          field="PotentialEffectsOfFailure"
          title="潜在失效后果"
          :span="12"
          :item-render="{}"
        >
          <template #default="{ data }">
            <vxe-textarea
              v-model="data.PotentialEffectsOfFailure"
              placeholder="请输入潜在失效后果"
              :autosize="{ minRows: 4, maxRows: 6 }"
            ></vxe-textarea>
          </template>
        </vxe-form-item>
        <vxe-form-item
          field="Severity"
          title="严重度S"
          :span="12"
          :item-render="{}"
        >
          <template #default="{ data }">
            <vxe-input
              v-model="data.Severity"
              type="number"
              placeholder="严重度S"
            ></vxe-input>
          </template>
        </vxe-form-item>
        <vxe-form-item field="Class" title="分类" :span="12" :item-render="{}">
          <template #default="{ data }">
            <vxe-textarea
              v-model="data.Class"
              placeholder="请输入分类"
              :autosize="{ minRows: 4, maxRows: 6 }"
            ></vxe-textarea>
          </template>
        </vxe-form-item>
        <vxe-form-item
          field="PotentialCausesOfFailure"
          title="潜在失效原因"
          :span="12"
          :item-render="{}"
        >
          <template #default="{ data }">
            <vxe-textarea
              v-model="data.PotentialCausesOfFailure"
              placeholder="请输入潜在失效原因"
              :autosize="{ minRows: 4, maxRows: 6 }"
            ></vxe-textarea>
          </template>
        </vxe-form-item>
        <vxe-form-item
          field="Occurence"
          title="频度O"
          :span="12"
          :item-render="{}"
        >
          <template #default="{ data }">
            <vxe-input
              v-model="data.Occurence"
              type="number"
              placeholder="频度O"
            ></vxe-input>
          </template>
        </vxe-form-item>
        <vxe-form-item
          field="CurrentProcessControlsPrevention"
          title="控制预防"
          :span="12"
          :item-render="{}"
        >
          <template #default="{ data }">
            <vxe-textarea
              v-model="data.CurrentProcessControlsPrevention"
              placeholder="请输入控制预防"
              :autosize="{ minRows: 4, maxRows: 6 }"
            ></vxe-textarea>
          </template>
        </vxe-form-item>
        <vxe-form-item
          field="CurrentProcessControlsDetection"
          title="控制探测"
          :span="12"
          :item-render="{}"
        >
          <template #default="{ data }">
            <vxe-textarea
              v-model="data.CurrentProcessControlsDetection"
              placeholder="请输入控制探测"
              :autosize="{ minRows: 4, maxRows: 6 }"
            ></vxe-textarea>
          </template>
        </vxe-form-item>
        <vxe-form-item
          field="Detection"
          title="探测度D"
          :span="12"
          :item-render="{}"
        >
          <template #default="{ data }">
            <vxe-input
              v-model="data.Detection"
              type="number"
              placeholder="探测度D"
            ></vxe-input>
          </template>
        </vxe-form-item>
        <vxe-form-item field="Rpn" title="RPN" :span="12" :item-render="{}">
          <template #default="{ data }">
            <vxe-input
              v-model="data.Rpn"
              type="number"
              placeholder="RPN"
            ></vxe-input>
          </template>
        </vxe-form-item>
        <vxe-form-item
          field="SeverZone"
          title="严重区"
          :span="12"
          :item-render="{}"
        >
          <template #default="{ data }">
            <vxe-input
              v-model="data.SeverZone"
              type="number"
              placeholder="严重区"
            ></vxe-input>
          </template>
        </vxe-form-item>
        <vxe-form-item
          field="DetectZone"
          title="探测区"
          :span="12"
          :item-render="{}"
        >
          <template #default="{ data }">
            <vxe-input
              v-model="data.DetectZone"
              type="number"
              placeholder="探测区"
            ></vxe-input>
          </template>
        </vxe-form-item>
        <vxe-form-item
          field="RiskPriorLevel"
          title="RPL"
          :span="12"
          :item-render="{}"
        >
          <template #default="{ data }">
            <vxe-input
              v-model="data.RiskPriorLevel"
              type="number"
              placeholder="RPL"
            ></vxe-input>
          </template>
        </vxe-form-item>
        <vxe-form-item
          title="措施执行结果"
          title-align="left"
          :title-width="200"
          :span="24"
          :title-prefix="{ icon: 'vxe-icon--success' }"
        ></vxe-form-item>
        <vxe-form-item
          field="RecommendedActions"
          title="建议措施"
          :span="24"
          :item-render="{}"
        >
          <template #default="{ data }">
            <vxe-textarea
              v-model="data.RecommendedActions"
              placeholder="请输入建议措施"
              :autosize="{ minRows: 3, maxRows: 4 }"
            ></vxe-textarea>
          </template>
        </vxe-form-item>

        <vxe-form-item
          field="ResponsibilityAndTargetCompletionDate"
          title="责任人和目标完成日期"
          :span="24"
          :item-render="{}"
        >
          <template #default="{ data }">
            <vxe-textarea
              v-model="data.ResponsibilityAndTargetCompletionDate"
              placeholder="请输入责任人和目标完成日期"
              :autosize="{ minRows: 3, maxRows: 4 }"
            ></vxe-textarea>
          </template>
        </vxe-form-item>

        <vxe-form-item
          field="ActionTaken"
          title="实施对策"
          :span="24"
          :item-render="{}"
        >
          <template #default="{ data }">
            <vxe-textarea
              v-model="data.ActionTaken"
              placeholder="请输入实施对策"
              :autosize="{ minRows: 3, maxRows: 4 }"
            ></vxe-textarea>
          </template>
        </vxe-form-item>
        <vxe-form-item
          field="ActionTakenSeverity"
          title="严重度S"
          :span="12"
          :item-render="{}"
        >
          <template #default="{ data }">
            <vxe-input
              v-model="data.ActionTakenSeverity"
              type="number"
              placeholder="严重度S"
            ></vxe-input>
          </template>
        </vxe-form-item>
        <vxe-form-item
          field="ActionTakenOccurence"
          title="频度O"
          :span="12"
          :item-render="{}"
        >
          <template #default="{ data }">
            <vxe-input
              v-model="data.ActionTakenOccurence"
              type="number"
              placeholder="频度O"
            ></vxe-input>
          </template>
        </vxe-form-item>
        <vxe-form-item
          field="ActionTakenDetection"
          title="探测度D"
          :span="12"
          :item-render="{}"
        >
          <template #default="{ data }">
            <vxe-input
              v-model="data.ActionTakenDetection"
              type="number"
              placeholder="探测度D"
            ></vxe-input>
          </template>
        </vxe-form-item>
        <vxe-form-item
          field="ActionTakenRpn"
          title="RPN"
          :span="12"
          :item-render="{}"
        >
          <template #default="{ data }">
            <vxe-input
              v-model="data.ActionTakenRpn"
              type="number"
              placeholder="RPN"
            ></vxe-input>
          </template>
        </vxe-form-item>
        <vxe-form-item align="center" title-align="left" :span="24">
          <template #default>
            <vxe-button type="submit" style="background-color: skyblue"
              >提交</vxe-button
            >
            <vxe-button type="reset" style="background-color: lightgreen"
              >重置</vxe-button
            >
          </template>
        </vxe-form-item>
      </vxe-form>
    </template>
  </vxe-modal>
</template>

<style lang="scss" scoped></style>
